package br.com.dev.tcc.connection;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import br.com.dev.tcc.R;
import br.com.dev.tcc.bean.Apolice;
import br.com.dev.tcc.bean.Corretor;
import br.com.dev.tcc.bean.Mecanica;
import br.com.dev.tcc.bean.Plano;
import br.com.dev.tcc.bean.ResponseData;
import br.com.dev.tcc.bean.Segurado;
import br.com.dev.tcc.bean.Veiculo;
import br.com.dev.tcc.bean.sinistro.Sinistro;
import br.com.dev.tcc.util.CalendarParser;

/**
 * 
 * 
 * @author
 * 
 */
public class WSClient {

	private static final String NAMESPACE = "http://tcc.com.br";

	private static final String URL = "http://192.168.0.142:8080/WSTCC/services/ServicoA?wsdl";
	// private static final String URL = "http://192.168.1.33:8080/WSTCC/services/ServicoA?wsdl";
	// private static final String URL = "http://10.0.2.2:8080/WSTCC/services/ServicoA?wsdl";

	private static final int TIMEOUT = 20000;

	private static final int RES_ID_DEFAULT_MESSAGE = R.string.erro_default;

	public WSClient() {
	}

	@SuppressWarnings("deprecation")
	public ResponseData<Sinistro> inserirSinistro(Context context,
			SinistroWrapperWS w, Vector<String> v) {

		// Namespace e nome para o objeto SOAP
		String method_name = "inserirSinistro";
		String soap_action = "http://tcc.com.br/inserirSinistro";
		SoapObject soap = new SoapObject(NAMESPACE, method_name);

		PropertyInfo pi = new PropertyInfo();
		pi.name = "wrapper";

		pi.type = w.getClass();

		soap.addProperty(pi, w);

		soap.addProperty("partes", v);

		// Cria o envelope com o objeto SOAP
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);
		envelope.dotNet = true;
		envelope.addMapping("http://tcc.com.br/xsd", "SinistroWrapperWS",
				SinistroWrapperWS.class);

		// Cria o HttpTransport para enviar os dados (SOAP)
		HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT);

		boolean success = true;
		String message = null;
		Sinistro data = null;

		// Faz a requisição
		try {
			httpTransport.call(soap_action, envelope);

			SoapObject response = (SoapObject) envelope.bodyIn;

			String msg = response.getProperty(0).toString(); // mensagem

			String id = response.getProperty(1).toString(); // idSinistro

			data = new Sinistro();
			data.setId(Integer.parseInt(id));
			data.setStatusMensagem(msg);
		} catch (Exception e) {
			success = false;
			message = context.getString(RES_ID_DEFAULT_MESSAGE);
		}

		return new ResponseData<Sinistro>(success, message, data);
	}

	public ResponseData<Apolice> buscarApolice(Context context, String CPF,
			String placa, String cor) {

		// Namespace e nome para o objeto SOAP
		String method_name = "buscarApolice";
		String soap_action = "http://tcc.com.br/buscarApolice";
		SoapObject soap = new SoapObject(NAMESPACE, method_name);

		// Adiciona os parâmetros para a soma
		soap.addProperty("cpf", CPF);
		soap.addProperty("placa", placa);
		soap.addProperty("cor", cor);

		// Cria o envelope com o objeto SOAP
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);
		envelope.dotNet = true;

		// Cria o HttpTransport para enviar os dados (SOAP)
		HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT);

		String errorMessage = null;
		boolean success = false;
		Apolice a = null;

		// Faz a requisição
		try {
			httpTransport.call(soap_action, envelope);

			SoapObject response = (SoapObject) envelope.bodyIn;

			int propertyCount = response.getPropertyCount();

			if (propertyCount > 0) {

				success = true;

				a = new Apolice();
				a.setId(Integer.parseInt(response.getProperty(0).toString()));
				a.setHash(response.getProperty(1).toString());
				a.setVencimento(CalendarParser.getCalendar(response
						.getProperty(2).toString()));
				Plano p = new Plano();
				p.setId(Integer.parseInt(response.getProperty(3).toString()));
				a.setPlano(p);
				Segurado s = new Segurado();
				s.setNome(response.getProperty(4).toString());
				a.setSegurado(s);
				Veiculo v = new Veiculo();
				v.setModelo(response.getProperty(5).toString());
				v.setPlaca(response.getProperty(6).toString());
				v.setCor(response.getProperty(7).toString());
				a.setVeiculo(v);
				Corretor c = new Corretor();
				c.setName(response.getProperty(8).toString());
				c.setEmail(response.getProperty(9).toString());
				if (propertyCount > 9) {
					String tel;
					for (int i = 10; i < propertyCount; i++) {
						tel = response.getProperty(i).toString();
						c.addPhone(tel);
					}
				}
				a.setCorretor(c);
			} else {
				errorMessage = context.getString(R.string.erro_buscar_apolice);
			}
		} catch (Exception e) {
			errorMessage = context.getString(RES_ID_DEFAULT_MESSAGE);
		}

		return new ResponseData<Apolice>(success, errorMessage, a);
	}

	public ResponseData<String[]> buscarStatusSinistro(Context context,
			int idSinistro) {

		// Namespace e nome para o objeto SOAP
		String method_name = "buscarStatusSinistro";
		String soap_action = "http://tcc.com.br/buscarStatusSinistro";
		SoapObject soap = new SoapObject(NAMESPACE, method_name);

		soap.addProperty("idSinistro", idSinistro);

		// Cria o envelope com o objeto SOAP
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);
		envelope.dotNet = true;

		// Cria o HttpTransport para enviar os dados (SOAP)
		HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT);

		boolean success = true;
		String message = null;
		String[] data = null;

		// Faz a requisição
		try {
			httpTransport.call(soap_action, envelope);

			SoapObject response = (SoapObject) envelope.bodyIn;

			String status = response.getProperty(0).toString(); // status
			String msg = response.getProperty(1).toString(); // msg status
																// detalhada

			data = new String[] { status, msg };
		} catch (Exception e) {
			success = false;
			message = context.getString(RES_ID_DEFAULT_MESSAGE);
		}

		return new ResponseData<String[]>(success, message, data);
	}

	public ArrayList<Mecanica> buscarEnderecosMecanica(Context context)
			throws Exception {

		// Namespace e nome para o objeto SOAP
		String method_name = "buscarEnderecoMecanica";
		String soap_action = "http://tcc.com.br/buscarEnderecoMecanica";
		SoapObject soap = new SoapObject(NAMESPACE, method_name);

		// Cria o envelope com o objeto SOAP
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);
		envelope.dotNet = true;

		// Cria o HttpTransport para enviar os dados (SOAP)
		HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT);

		ArrayList<Mecanica> lista = null;

		// Faz a requisição
		try {
			httpTransport.call(soap_action, envelope);

			SoapObject response = (SoapObject) envelope.bodyIn;

			lista = new ArrayList<Mecanica>();

			for (int i = 0; i < response.getPropertyCount(); i++) {

				SoapObject m = (SoapObject) response.getProperty(i);

				Mecanica mecanica = new Mecanica();

				mecanica.setNome(m.getProperty(4).toString());
				mecanica.setEndereco(m.getProperty(0).toString());
				mecanica.setLatitude(m.getProperty(2).toString());
				mecanica.setLongitude(m.getProperty(3).toString());

				lista.add(mecanica);
			}
		} catch (SocketTimeoutException e) {
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE));
		} catch (IOException e) {
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE));
		} catch (XmlPullParserException e) {
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE));
		}

		return lista;
	}

	public ArrayList<SinistroRetorno> buscarDadosSinistro(Context context,
			int idApolice) throws Exception {

		// Namespace e nome para o objeto SOAP
		String method_name = "buscarDadosSinistro";
		String soap_action = "http://tcc.com.br/buscarDadosSinistro";
		SoapObject soap = new SoapObject(NAMESPACE, method_name);

		soap.addProperty("idApolice", idApolice);

		// Cria o envelope com o objeto SOAP
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soap);
		envelope.dotNet = true;

		// Cria o HttpTransport para enviar os dados (SOAP)
		HttpTransportSE httpTransport = new HttpTransportSE(URL, TIMEOUT);

		// Faz a requisição
		try {
			httpTransport.call(soap_action, envelope);

			SoapObject response = (SoapObject) envelope.bodyIn;

			int count = response.getPropertyCount();
			if (count == 0)
				throw new IllegalStateException(
						context.getString(R.string.erro_buscar_sinistros));

			ArrayList<SinistroRetorno> lista = new ArrayList<SinistroRetorno>();

			for (int i = 0; i < response.getPropertyCount(); i++) {

				SoapObject m = (SoapObject) response.getProperty(i);

				SinistroRetorno s = new SinistroRetorno();

				s.setId(Integer.parseInt(m.getProperty(3).toString()));
				s.setIdApolice(Integer.parseInt(m.getProperty(4).toString()));
				s.setData(m.getProperty(0).toString());
				s.setStatus(m.getProperty(7).toString());
				s.setMensagemStatus(m.getProperty(5).toString());
				s.setTipo(m.getProperty(8).toString());
				s.setEndereco(m.getProperty(2).toString());
				s.setDescricao(m.getProperty(1).toString());

				lista.add(s);
			}

			return lista;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE));
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE), e);
		} catch (XmlPullParserException e) {
			e.printStackTrace();
			throw new Exception(context.getString(RES_ID_DEFAULT_MESSAGE));
		}
	}
}
